package com.fengli.task.controller;

import com.fengli.task.entity.UserEntity;
import com.fengli.task.service.UserService;
import com.fengli.task.uitl.Result;
import com.fengli.task.uitl.enumType.Code;
import com.fengli.task.uitl.exception.ParamException;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    //提供用户相关的服务
    @Autowired
    private UserService userService;

    /**
     * 此api用于登陆()
     * @param userEntity
     * @param bindingResult
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login( @Validated  UserEntity userEntity, BindingResult bindingResult) {
        /*校验邮箱格式,该controller我使用springboot的校验*/
        if (bindingResult.hasErrors()) {
            List<ObjectError> list = bindingResult.getAllErrors();
            throw new ParamException(list.get(0).getDefaultMessage());
        }
        //调用Service，由于我们做了统一异常处理,这里我们就不做处理了（并且我们的异常处理不会写在Service层了）
        boolean s= userService.matchUser(userEntity.getEmail(),userEntity.getPassword());
        userEntity = userService.findUser(userEntity.getEmail(),userEntity.getPassword());
        /*封住结果*/
        Result result;
        if(s == true){
            result =new Result("登陆成功",Code.SUCCESS,userEntity.getId());
        }else {
            result = new Result("没有该用户",Code.FAIL,null);
        }

        return result;
    }

    /**
     * 此api用于注册
     *
     * @param userEntity
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/signUp", method = RequestMethod.POST)
    @ResponseBody
    public Result sigup(@Validated  UserEntity userEntity, BindingResult bindingResult) {
        /*校验邮箱格式,该controller我使用springboot的校验*/
        if (bindingResult.hasErrors()) {
            List<ObjectError> list = bindingResult.getAllErrors();
            throw new ParamException(list.get(0).getDefaultMessage());
        }

        //调用userService,userService.createUser();
        boolean status = userService.addUser(userEntity.getEmail(), userEntity.getPassword());
        Result result;
        result = new Result("注册用户成功", Code.SUCCESS, true);
        return result;
    }

    /**
     * todo 注销登陆
     *
     * @return
     */
    public Map<String, String> logout() {
        return null;
    }
}
